/**
 * 
 */
package cn.antia.cep.page.action;

import java.util.*;
import java.text.*;
import javax.servlet.http.*;

import cn.antia.cep.common.*;
import cn.antia.cep.db.hibernate.bean.*;
import cn.antia.cep.busi.*;
import cn.antia.cwin.page.StrutsAction;

/**
 * @author sunkeei
 *
 */
public class UserAction extends StrutsAction {
	private String action;
	
	private UserService userService;
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	protected String action() throws AntiaException {
		List messages = new LinkedList();
		if(action.equalsIgnoreCase("add")){
			return add();
		}else if(action.equalsIgnoreCase("update")){
			return update();
		}else if(action.equalsIgnoreCase("delete")){
			return delete();
		}else if(action.equalsIgnoreCase("query")){
			return query();
		}else if(action.equalsIgnoreCase("toEdit")){
			return toEdit();
		}else if(action.equalsIgnoreCase("myValidator")){
			return myValidator();
		}else if(action.equals("gp_step1")){
			return gpStep1();
		}else if(action.equals("gp_step2")){
			return gpStep2();
		}else if(action.equals("gp_step3")){
			return gpStep3();
		}
		else{		
			messages.add("传入了错误的操作类型！");
			request.setAttribute("messages", messages);
			return "error";
		}
	}

    /**
     * 新增用户
     * @param mapping ActionMapping
     * @param request HttpServletRequest
     * @return ActionForward
     * @throws AntiaException e
     */
	private String add() throws AntiaException {
		User user = new User();
		List messages = new LinkedList();
		//是否出错
		boolean isOccurError = false;
		//检测验证码
		String num=request.getParameter("num"); 
		String random=(String)session.getAttribute("random");
		if(num!=null&&random!=null){ 
			if(!num.equals(random)){ 
				isOccurError = true;
				messages.add("对不起，验证码错误。"); 
			}	
		} 
		
		//检测用户名与EMAIL地址是否重复
		String nickname = request.getParameter("nickname");
		if(nickname == null || nickname.trim().equals("")){
			isOccurError = true;
			messages.add("用户名不能为空。");
		}else if(nickname.trim().length()>=20){
			isOccurError = true;
			messages.add("用户名长度超出。");
		}else{		
			user.setValid(null);
			user.setNickname(nickname.trim());
			user.setModifyTime(null);
			if(userService.isExistEntity(user)){
				messages.add("对不起，用户名" + nickname + "已经存在。");
				isOccurError = true;
			}
		}
		String email = request.getParameter("email");
		if(email != null && !email.trim().equals("")){
			email = email.trim();
			user.setEmail(email);
			user.setNickname(null);
			user.setValid(null);
			if(userService.isExistEntity(user)){
				messages.add("对不起，这个Email地址已经注册过一个帐号。");
				isOccurError = true;
			}
		}
		//设置用户名
		user.setNickname(nickname);
		//检测密码是否一致
		String password1 = request.getParameter("password");
		String password2 = request.getParameter("password2");
		
		if(!password1.equals(password2)){
			messages.add("对不起，您的两次密码输入不相同。");
			isOccurError = true;
		}else{
			//密码加密
			String password = SampleEncryption.getEncryptString(password1);
			//设置密码
			user.setPassword(password);
		}
		
		//生日
		String dateString = request.getParameter("birthday");
		Date birt = null;
		if(dateString != null){
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");
			try{
				birt = dateFormat.parse(dateString);
			}catch(Exception e){
				messages.add("生日日期格式错误！");
			}
		}
		//设置年龄
		if(birt != null){
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(birt);
			Calendar now = Calendar.getInstance();
			user.setAge(new Integer(now.get(Calendar.YEAR) - calendar.get(Calendar.YEAR)));
		}
		//生日
		user.setBirthday(birt);
		request.setAttribute("regesterBirth", dateString);
		//设置安全问题
		String passQuestion = request.getParameter("passQuestion");
		String passQuestionAnswer = request.getParameter("passQuestionAnswer");
		if(passQuestion == null || passQuestion.trim().length() < 1 || passQuestionAnswer == null || passQuestionAnswer.trim().length() < 1){
			messages.add("对不起，您没有选择密码问题或没有填写密码问题的答案。");
			isOccurError = true;
		}
		user.setPassQuestion(passQuestion);
		user.setPassQuestionAnswer(passQuestionAnswer);
		//学历
		user.setDegree(request.getParameter("degree"));
		//真实姓名
		user.setName(request.getParameter("name"));
		//自我介绍
		user.setMyIntroduction(request.getParameter("myIntroduction"));
		//注册时间
		user.setRegisterTime(new Date());
		//用户类型
		user.setUserType(new Integer(request.getParameter("userType")));
		//设置其有效
		user.setValid(new Integer(DBFlag.VALID));
		//性别
		user.setSex(request.getParameter("gender"));
		//电话
		user.setTel(request.getParameter("tel"));
		//地址
		user.setAddress(request.getParameter("address"));
		//设置为登录
		user.setLastLogonTime(new Date());
		user.setLogonTimes(new Integer(1));
		//如果发生了错误，则设置错误信息，并将用户信息写回原页面
		if(isOccurError){
			request.setAttribute("registerUser", user);
			//设置错误消息
			request.setAttribute("messages", messages);
			//返回
			return "register_failure";
		}else{
			//创建用户
			userService.addUser(user);
		}
		request.setAttribute("registerNickname", nickname);
		return "register_success";
	}
	
	/**
	 * 更新用户
     * @param mapping ActionMapping
     * @param request HttpServletRequest
     * @return ActionForward
     * @throws AntiaException e
	 * */
	private String update() throws AntiaException {
		User user = new User();
		String id = request.getParameter("id");
		if(id == null || id.trim().length() < 1){
			messages.add("更新用户失败！没有用户主键！");
			isOccurError = true;
		}else{
			user = getUser(Integer.parseInt(id));
			if(user == null){
				messages.add("更新用户失败！没有找到要更新的用户！");
				isOccurError = true;
				user = new User();
			}else{
				user.setId(new Integer(id));
			}
		}
		List messages = new LinkedList();
		user.setNickname(request.getParameter("nickname"));
		//用户名
		String name = request.getParameter("name");
		if(name != null){
			user.setName(name.trim());
		}
		//修改密码
		if(request.getParameter("isUpdatePwd")!=null){
			String oldPassword = request.getParameter("oldPassword");
			if(oldPassword != null && oldPassword.trim().length() > 0){
				User u = new User();
				u.setModifyTime(null);
				u.setId(new Integer(id));
				u.setPassword(SampleEncryption.getEncryptString(oldPassword));
				if(!userService.isExistEntity(u)){
					messages.add("更新用户失败，密码错误！");
					isOccurError = true;
				}else{
					String p1 = request.getParameter("password");
					String p2 = request.getParameter("password2");
					if(p1 != null && p2 != null && p1.equals(p2)){
						user.setPassword(SampleEncryption.getEncryptString(p1));
					}
				}
			}
		}
		if(request.getParameter("isSetPwdQuest") != null){
			String oldPassword = request.getParameter("password3");
			if(oldPassword != null && oldPassword.trim().length() > 0){
				User u = new User();
				u.setModifyTime(null);
				u.setId(new Integer(id));
				u.setPassword(SampleEncryption.getEncryptString(oldPassword));
				if(!userService.isExistEntity(u)){
					messages.add("更新用户失败，密码错误！");
					isOccurError = true;
				}else{
					String p1 = request.getParameter("passQuestion");
					String p2 = request.getParameter("passQuestionAnswer");
					if(p1 != null && p2 != null && p2.trim().length() > 3){
						user.setPassQuestion(p1);
						user.setPassQuestionAnswer(p2);
					}
				}
			}
		}
		//生日
		String dateString = request.getParameter("birthday");
		Date birt = null;
		if(dateString != null){
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");
			try{
				birt = dateFormat.parse(dateString);
			}catch(Exception e){
				messages.add("生日日期格式错误！");
			}
		}
		//设置年龄
		if(birt != null){
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(birt);
			Calendar now = Calendar.getInstance();
			user.setAge(new Integer(now.get(Calendar.YEAR) - calendar.get(Calendar.YEAR)));
		}
		user.setBirthday(birt);
		user.setDegree(request.getParameter("degree"));
		user.setMyIntroduction(request.getParameter("myIntroduction"));
		user.setUserType(new Integer(request.getParameter("userType")));
		user.setSex(request.getParameter("gender"));
		user.setTel(request.getParameter("tel"));
		user.setAddress(request.getParameter("address"));
		user.setModifyTime(new Date());
		//查看是否有设为失效的标志
		if(request.getParameter("valid") != null){
			user.setValid(new Integer(request.getParameter("valid")));
		}
		if(isOccurError){
			request.setAttribute("user", user);
			request.setAttribute("messages", messages);
			return "update_failure";
		}
		//更新用户
		userService.update(user);
		request.setAttribute("user", user);
		request.setAttribute("myMessage", "用户信息更新成功,点击这里返回首页。");
		//返回
		return "update_success";
	}
	
	/**
	 * 删除用户
     * @param mapping ActionMapping
     * @param request HttpServletRequest
     * @return ActionForward
     * @throws AntiaException e
	 * */
	private String delete() throws AntiaException {
		User user = new User();
		List messages = new LinkedList();
		String id = request.getParameter("id");
		boolean isOccurError = false;
		if(id == null || id.trim().length() < 1){
			isOccurError = true;
			messages.add("注销用户失败！没有用户主键！");
		}
		user.setId(new Integer(id));
		//设用户标志为删除
		user.setValid(new Integer(DBFlag.USER_DELETE));
		//设置删除时间
		user.setModifyTime(new Date());
		if(!isOccurError){
			userService.update(user);
		}else{
			request.setAttribute("messages", messages);
		}
		return "delete_success";
	}
	
	/**
	 * 查询用户
     * @param mapping ActionMapping
     * @param request HttpServletRequest
     * @return ActionForward
     * @throws AntiaException e
	 * */
	private String query() throws AntiaException {
		User user = new User();
		user.setName(request.getParameter("name"));
		String isStrict = request.getParameter("strict");
		List userlist;
		if(isStrict != null && isStrict.equals("1")){
			userlist = userService.find(user, true);
		}else{
			userlist = userService.find(user, false);
		}
		HttpSession session = request.getSession();
		session.setAttribute("queryUserList",userlist );
		return "query_success";
	}
	
	/**
	 * 到更新页面
     * @param mapping ActionMapping
     * @param request HttpServletRequest
     * @return ActionForward
     * @throws AntiaException e
	 * */
	private String toEdit() throws AntiaException {
		String id = request.getParameter("id");
		if(id == null || id.trim().length() < 1){
			return "error";
		}
		User user = userService.get(User.class, new Integer(id));
		if(user == null){
			return "error";
		}
		request.setAttribute("user", user);
		return "update_success";
	}
	
	private User getUser(int id)throws AntiaException{
		User user = userService.get(User.class, new Integer(id));
		if(user == null){
			request.setAttribute("message", "更新用户失败！没有用户主键！");
			return null;
		}
		return user;
	}
	
	/**
	 * 验证用户名
     * @param mapping ActionMapping
     * @param request HttpServletRequest
     * @return ActionForward
     * @throws AntiaException e
	 * */
	private String myValidator() throws AntiaException {
		String nickname = request.getParameter("nickname");
		User user=new User();
		if(nickname == null || nickname.trim().equals("")){
			request.setAttribute("validatorMessage", "用户名不能为空");
		}else if(nickname.trim().length()>=20){
			request.setAttribute("validatorMessage", "用户名过长");
		}else{			
			user.setNickname(nickname.trim());
			user.setModifyTime(null);
			if(userService.isExistEntity(user)){
				String message="用户名 " + nickname + " 已经存在。";
				request.setAttribute("validatorMessage", message);
			}else{
				String message="恭喜您! " + nickname + " 可以使用。";
				request.setAttribute("validatorMessage", message);
			}
		}
		return "myValidator_success";	
	}
	/**
	 * 取回密码，第一步
     * @param mapping ActionMapping
     * @param request HttpServletRequest
     * @return ActionForward
     * @throws AntiaException e
	 * */
	private String gpStep1() throws AntiaException {
		String nickname = request.getParameter("username");
		String doorDog = request.getParameter("doorDog");
		String rand = (String)session.getAttribute("gp_step1_v");
		session.removeAttribute("gp_step1_v");
		if(!doorDog.equals(rand)){
			request.setAttribute("message", "对不起，验证码错误。");
			return "gp_step_1";
		}
		User user = new User();
		user.setNickname(nickname);
		user.setModifyTime(null);
		List users = userService.find(user, true);
		if(users != null && users.size() == 1){
			user = (User)users.get(0);
			if(user.getPassQuestion() != null){
				request.setAttribute("user", user);
				return "gp_step_2";
			}else{
				request.setAttribute("message", "对不起，您没有设置密码提示问题。所以无法进行此操作。");
				request.setAttribute("nor", "y");
				return "gp_step_1";
			}
		}else{
			String message="对不起，您输入的用户名不存在。";
			request.setAttribute("message", message);
			return "gp_step_1";
		}
	}
	/**
	 * 取回密码，第二步
     * @param mapping ActionMapping
     * @param request HttpServletRequest
     * @return ActionForward
     * @throws AntiaException e
	 * */
	private String gpStep2() throws AntiaException {
		String sid = request.getParameter("userId");
		int id = Integer.parseInt(sid);
		String answer = request.getParameter("answer");
		
		User user = userService.get(User.class, id);
		if(user != null){
			if(user.getPassQuestionAnswer() != null && user.getPassQuestionAnswer().equals(answer)){
				session.setAttribute("cuserId_pg", user.getId() + "");
				return "gp_step_3";
			}else{
				request.setAttribute("user", user);
				request.setAttribute("message", "提示问题答案回答错误。");
				return "gp_step_2";
			}
		}else{
			String message="对不起，用户不存在。";
			request.setAttribute("message", message);
			return "error";
		}
	}
	/**
	 * 取回密码，第三步
     * @param mapping ActionMapping
     * @param request HttpServletRequest
     * @return ActionForward
     * @throws AntiaException e
	 * */
	private String gpStep3() throws AntiaException {
		String sid = request.getParameter("userId");
		String suid = (String)session.getAttribute("cuserId_pg");
		
		if(!sid.equals(suid)){
			request.setAttribute("message", "非法操作。服务器没有预备此用户的取回密码操作。IP：" + request.getRemoteAddr());
			return "error";
		}
		String p1 = request.getParameter("password");
		String p2 = request.getParameter("password2");
		if(p1 != null && p2 != null){
			p1 = p1.trim();
			p2 = p2.trim();
			if(p1.equals(p2) && p1.length() > 5){
				User user = userService.get(User.class, new Integer(sid));
				user.setPassword(SampleEncryption.getEncryptString(p1));
				userService.update(user);
				request.setAttribute("message", "修改密码成功。");
				session.removeAttribute("cuserId_pg");
				return "gp_step_4";
			}else{
				request.setAttribute("message", "两次密码输入不相同或密码长度不够。");
				return "gp_step_3";
			}
		}else{
			request.setAttribute("message", "您输入的密码为空。");
			return "gp_step_3";
		}
	}

	public void setAction(String action) {
		this.action = action;
	}
}